<?php
namespace app\service;

use app\model\{ChatSession, ChatMessage, User};
use think\facade\Log;
use Exception;

class AiChatService
{
    protected $chatService;
    protected $aiService;
    protected $aiHistoryService;
    protected $topicCompletionService;

    public function __construct()
    {
        $this->chatService = new ChatService();
        $this->aiService = new AiService();
        $this->aiHistoryService = new AiHistoryService($this->aiService);
        $this->topicCompletionService = new TopicCompletionService();
    }

    /**
     * 处理AI聊天请求
     */
    public function handleChatRequest(User $user, string $content, ?int $sessionId = null): array
    {
        if (empty($sessionId)) {
            $session = $this->chatService->createSession($user, [
                'title' => mb_substr($content, 0, 20) . '...'
            ]);
            $sessionId = $session->id;
        }

        // 保存用户消息
        $userMessage = $this->chatService->sendMessage($sessionId, $user, $content);

        // 创建AI消息记录
        $aiMessage = new ChatMessage;
        $aiMessage->session_id = $sessionId;
        $aiMessage->user_id = $user->id;
        $aiMessage->message_type = ChatMessage::TYPE_TEXT;
        $aiMessage->content = '';
        $aiMessage->is_ai = true;
        $aiMessage->save();

        // 获取历史消息
        $history = $this->chatService->getSessionHistory($sessionId);

        return [
            'message_id' => $aiMessage->id,
            'session_id' => $sessionId,
            'history' => $history
        ];
    }

    /**
     * 处理AI流式响应
     * 
     * 根据消息ID获取AI消息记录,查询会话并提取生成上下文提示
     * 添加系统提示,检查话题完成度,处理历史消息(必要时缩略汇总上下文)
     * 返回AI消息、处理后的历史记录和会话信息
     * 
     * @param int $messageId AI消息ID
     * @param User $user 用户对象
     * @param callable|null $callback 回调函数
     * @return array 包含AI消息、历史记录和会话信息的数组
     */
    public function handleStreamResponse(int $messageId, User $user, callable $callback = null)
    {
        // Log::debug('开始处理AI流式响应：' . json_encode([
        //     'message_id' => $messageId,
        //     'user_id' => $user->id
        // ], JSON_UNESCAPED_UNICODE));

        $aiMessage = $this->validateAiMessage($messageId);
        // Log::debug('AI消息验证通过：' . json_encode([
        //     'message' => $aiMessage->toArray()
        // ], JSON_UNESCAPED_UNICODE));
        
        $sessionInfo = $this->getSessionInfo($aiMessage->session_id);
        // Log::debug('获取会话信息：' . json_encode([
        //     'session_info' => $sessionInfo
        // ], JSON_UNESCAPED_UNICODE));

        $history = $this->chatService->getSessionHistory($aiMessage->session_id, $messageId);
        // Log::debug('获取历史消息：' . json_encode([
        //     'history_count' => count($history),
        //     'history' => $history
        // ], JSON_UNESCAPED_UNICODE));

        // 检查话题完成度
        $completionCheck = $this->topicCompletionService->checkCompletion(
            ChatSession::find($aiMessage->session_id),
            $user
        );
        
        // Log::debug('话题完成度检查结果：' . json_encode($completionCheck, JSON_UNESCAPED_UNICODE));
        
        // 添加系统角色提示
        $this->addSystemPrompt($history, $completionCheck['next'] === 1);
        // Log::debug('添加系统提示后的历史消息：' . json_encode([
        //     'history_count' => count($history),
        //     'history' => $history
        // ], JSON_UNESCAPED_UNICODE));

        // 处理历史消息
        $processedHistory = $this->aiHistoryService->processHistoryAndGenerateReply($history, $sessionInfo);
        // Log::debug('历史消息处理完成：' . json_encode([
        //     'processed_count' => count($processedHistory),
        //     'processed_history' => $processedHistory
        // ], JSON_UNESCAPED_UNICODE));

        return [
            'aiMessage' => $aiMessage,
            'history' => $processedHistory,
            'sessionInfo' => $sessionInfo
        ];
    }

    /**
     * 验证AI消息
     */
    protected function validateAiMessage(int $messageId): ChatMessage
    {
        $aiMessage = ChatMessage::where('id', $messageId)
            ->where('is_ai', true)
            ->find();

        if (!$aiMessage) {
            throw new Exception('消息不存在或无权限');
        }

        return $aiMessage;
    }

    /**
     * 获取会话信息
     */
    protected function getSessionInfo(int $sessionId): array
    {
        return \think\facade\Db::name('chat_sessions')
            ->where('id', $sessionId)
            ->field([
                'id',
                'summary',
                'last_summarized_message_id',
                'ai_analyzed_at'
            ])
            ->find();
    }

    /**
     * 添加系统提示
     */
    protected function addSystemPrompt(array &$history, bool $isNewTopic): void
    {
        $prompt = $isNewTopic
            ? "你是一位可爱的学习搭子，喜欢用简要、通俗易于理解的例子来解释各种知识点，性格古灵精怪，调皮，幽默，爱甩锅，喜欢八卦。你的聊天惜字如命，符合一个不太会打字的人类的聊天风格，请继续新的话题。"
            : "你是一位可爱的学习搭子，喜欢用简要、通俗易于理解的例子来解释各种知识点，性格古灵精怪，调皮，幽默，爱甩锅，喜欢八卦。请继续当前话题。";

        array_unshift($history, [
            'role' => 'system',
            'content' => $prompt
        ]);
    }

    /**
     * 处理学习会话请求
     * 
     * @param User $user 用户对象
     * @param int|null $courseId 课程ID
     * @param int|null $teachingPlanId 教案ID
     * @return array 包含会话信息的数组
     */
    public function handleLearningChatRequest(User $user, ?int $courseId = null, ?int $teachingPlanId = null): array
    {
        // 查询现有的学习记录和对应的会话
        $existingRecord = \think\facade\Db::table('learning_records')
            ->alias('lr')
            ->join('chat_sessions cs', 'cs.learning_records_id = lr.id')
            ->where('lr.user_id', $user->id)
            ->where(function ($query) use ($courseId, $teachingPlanId) {
                if ($courseId) {
                    $query->where('lr.course_id', $courseId);
                } else {
                    $query->where('lr.course_id', null)
                        ->where('lr.teaching_plan_id', $teachingPlanId);
                }
            })
            ->where('lr.delete_time', null)
            ->where('cs.delete_time', null)
            ->field([
                'lr.id as learning_records_id',
                'cs.id as session_id',
                'lr.current_plan_id',
                'lr.current_element_id',
                'lr.progress_rate',
                'lr.status'
            ])
            ->find();

        if ($existingRecord) {
            // 如果存在记录，获取历史会话
            $history = $this->chatService->getSessionHistory($existingRecord['session_id']);
            
            // 创建新的AI消息记录
            $aiMessage = new ChatMessage;
            $aiMessage->session_id = $existingRecord['session_id'];
            $aiMessage->user_id = $user->id;
            $aiMessage->message_type = ChatMessage::TYPE_TEXT;
            $aiMessage->content = '';
            $aiMessage->is_ai = true;
            $aiMessage->save();

            return [
                'message_id' => $aiMessage->id,
                'session_id' => $existingRecord['session_id'],
                'learning_records_id' => $existingRecord['learning_records_id'],
                'history' => $history,
                'progress' => [
                    'current_plan_id' => $existingRecord['current_plan_id'],
                    'current_element_id' => $existingRecord['current_element_id'],
                    'progress_rate' => $existingRecord['progress_rate'],
                    'status' => $existingRecord['status']
                ]
            ];
        } else {
            // 如果不存在记录，创建新的学习记录
            $learningRecord = \think\facade\Db::name('learning_records')->insertGetId([
                'user_id' => $user->id,
                'course_id' => $courseId,
                'teaching_plan_id' => $teachingPlanId,
                'learning_type' => 1, // 默认复习模式
                'status' => 0, // 进行中
                'created_at' => time(),
                'updated_at' => time(),
                'last_study_at' => time()
            ]);

            // 创建新的会话
            $session = $this->chatService->createSession($user, [
                'title' => $courseId ? '课程学习会话' : '教案学习会话',
                'session_type' => 4, // 学习会话
                'learning_records_id' => $learningRecord
            ]);

            // 创建AI消息记录
            $aiMessage = new ChatMessage;
            $aiMessage->session_id = $session->id;
            $aiMessage->user_id = $user->id;
            $aiMessage->message_type = ChatMessage::TYPE_TEXT;
            $aiMessage->content = '';
            $aiMessage->is_ai = true;
            $aiMessage->save();

            return [
                'message_id' => $aiMessage->id,
                'session_id' => $session->id,
                'learning_records_id' => $learningRecord,
                'history' => [],
                'progress' => [
                    'current_plan_id' => null,
                    'current_element_id' => null,
                    'progress_rate' => 0,
                    'status' => 0
                ]
            ];
        }
    }
} 